//
//  TabCategoryViewController.swift
//  AFNetworking
//
//  Created by admin on 2020/5/14.
//

import UIKit

class TabCategoryViewController: SupleViewController ,UITableViewDataSource,UITableViewDelegate{
    
    var dataList:NSMutableArray = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()

    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        updateData()
    }
    func configUI(){
        self.title = "分类管理"
        
        let navitem = UIBarButtonItem.init(customView: rightNavBtn)
        navigationItem.setRightBarButton(navitem, animated: true)
        
        view.addSubview(tableview)
        view.addSubview(addbtn)
    }
    
    
    
    
    lazy var tableview: UITableView = {
        () -> UITableView in
        let tableview = UITableView()
        tableview.dataSource = self
        tableview.delegate = self
        tableview.tableFooterView = UIView();
//        tableview.separatorStyle = .none
        return tableview
    }()
    lazy var clickBtn: UIButton = {
           () -> UIButton in
           let clickBtn = UIButton()
           clickBtn.titleLabel?.font = .systemFont(ofSize: 12);
           clickBtn.setTitle("test2313" ,for: .normal);
           clickBtn.setTitleColor(.white ,for: .normal);
           return clickBtn
       }()
    
    lazy var addbtn: UIButton = {
        () -> UIButton in
        let addbtn = UIButton()
        addbtn.ug_radius(4)
        addbtn.backgroundColor = COLORDANGER
        addbtn.setTitle("新增分类", for: .normal)
        addbtn.setTitleColor(UIColor.white, for: .normal)
        addbtn.ug_add(.touchUpInside) { (sender) in
            self.editTabCategory(categoryModen: nil)
        }
        return addbtn
    }()
    
    lazy var rightNavBtn: UIButton = {
        () -> UIButton in
        let rightNavBtn = UIButton()
        rightNavBtn.setTitle("排序", for: .normal)
        rightNavBtn.setTitle("完成", for: .selected)
        rightNavBtn.setTitleColor(COLORPRIMARY, for: .normal)
        rightNavBtn.ug_add(.touchUpInside) { (sender) in
            self.tableview.setEditing(!self.tableview.isEditing, animated: true)
            self.rightNavBtn.isSelected = self.tableview.isEditing
            if(!self.tableview.isEditing){
                self.sorf()
            }
        }
        return rightNavBtn
    }()
    
    func updateData() {
        Network.share().listTabCategoryshopId(StoreInfo.share().id) { (result, error) in
            if((error) != nil){
                let nserror:NSError = error! as NSError
                self.view.ug_msg(nserror.domain)
            }else{
                let temarr:NSArray = NSArray.modelArray(with: TabCategoryModen.self, json: result as Any)! as NSArray
                self.dataList = NSMutableArray.init(array: temarr)
                self.tableview.reloadData()
            }
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        tableview.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalTo(addbtn.snp_topMargin)
        }
        addbtn.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-KSAFE_Bottom)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(44)
        }
    }
}
// MARK:- UITableView
extension TabCategoryViewController{
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        let cellid = "cell"
        var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellid)
        if cell==nil {
            cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellid)
        }
        let celldata:TabCategoryModen = dataList[indexPath.row] as! TabCategoryModen
        cell?.textLabel?.text = celldata.name
        return cell!
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 44
    }
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .none
    }
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let topacticn = UITableViewRowAction.init(style: .normal, title: "置顶") { (action, indexPath) in
            let data = self.dataList[indexPath.row]
            self.dataList.removeObject(at: indexPath.row)
            self.dataList.insert(data, at: 0)
            self.sorf()
        }
        topacticn.backgroundColor = COLORWARNING;
        
        let delacticn = UITableViewRowAction.init(style: .normal, title: "删除") { (action, indexPath) in
            self.dataList.removeObject(at: indexPath.row)
            tableView.deselectRow(at: indexPath, animated: true)
            let celldata:TabCategoryModen = self.dataList[indexPath.row] as! TabCategoryModen
            self.delete(id: celldata.id!)
        }
        delacticn.backgroundColor = COLORDANGER;
        
        let editacticn = UITableViewRowAction.init(style: .normal, title: "编辑") { (action, indexPath) in
            self.editTabCategory(categoryModen: self.dataList.object(at: indexPath.row) as? TabCategoryModen)
        }
        editacticn.backgroundColor = COLORPRIMARY;
        
        return [editacticn,topacticn,delacticn];
    }
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let data = dataList[sourceIndexPath.row]
        dataList.removeObject(at: sourceIndexPath.row)
        dataList.insert(data, at: destinationIndexPath.row)
    }
//    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
//        return 10
//    }
//    func tableView(_ tableView: UITableView, viewForFotterInSection section: Int) -> UIView? {
//        return UIView()
//    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
    }
}

// MARK:- request
extension TabCategoryViewController{
    func create(name:String) {
        if name.count<=0 {
            self.view .ug_msg("分类名不能为空")
            return
        }
        Network.share().createTabCategory(name, shopId: StoreInfo.share().id, block: { (resule, error:Error?) in
            if((error) != nil){
                let nserror:NSError = error! as NSError
                self.view.ug_msg(nserror.domain)
            }else{
                let categoryModen = TabCategoryModen()
                categoryModen.name = name as String
                self.dataList.add(categoryModen)
                self.tableview.reloadData()
            }
        })
    }
    
    func delete(id:String) {
    
        Network.share().deleteTabCategory(id, block: { (resule, error:Error?) in
            if((error) != nil){
                let nserror:NSError = error! as NSError
                self.view.ug_msg(nserror.domain)
            }else{
                self.tableview.reloadData()
            }
        })
    }
    
    func update(tabCategory: TabCategoryModen) {
        if tabCategory.name?.count ?? 0 <= 0 {
            self.view .ug_msg("分类名不能为空")
            return
        }
        if tabCategory.name?.count ?? 0 <= 0 {
            self.view .ug_msg("请选择要修改的分类")
            return
        }
        let catedic:[AnyHashable : Any] = tabCategory.modelToJSONObject() as! [AnyHashable : Any]
        Network.share().updateTabCategory(tabCategory.id ?? "0", categoryDic: catedic , block:  { (resule, error:Error?) in
            if((error) != nil){
                let nserror:NSError = error! as NSError
                self.view.ug_msg(nserror.domain)
            }else{
                
                self.tableview.reloadData()
            }
        })
    }
    
    func sorf() {
        let dataobj = dataList.modelToJSONObject()
        Network.share().sorfTabCategory(dataobj as Any) { (result, error) in
            if((error) != nil){
                let nserror:NSError = error! as NSError
                self.view.ug_msg(nserror.domain)
            }else{
                self.updateData()
                
            }
        }
    }
    
}

// MARK: - 新增/修改UIAlert
extension TabCategoryViewController{
    
    func editTabCategory(categoryModen:TabCategoryModen?) {
        var msg:NSString = "新增分类"
        if (categoryModen != nil) {
            msg = "修改分类"
        }
        let alertController = UIAlertController(title: "提示", message: msg as String, preferredStyle: .alert)
        alertController.addTextField { (textField) in
            textField.placeholder = categoryModen?.name;
        }
        let commitAction = UIAlertAction(title: "确认", style: .default){ (action:UIAlertAction)in
            if(categoryModen != nil){
                categoryModen?.name = alertController.textFields?.first?.text
                self.update(tabCategory: categoryModen!)
            }else{
                let title = alertController.textFields?.first?.text;
                self.create(name: title ?? "")
      
            }
        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel){ (action:UIAlertAction)in
            
        }
        alertController.addAction(commitAction)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
    }
}
